package com.gack.business.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import io.jsonwebtoken.lang.Collections;


/**
 * 
 * @author ws
 * 2018-5-31
 */
@Repository
public class UserEnterpriseDepartmentPositionDao {

	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 将相应人员所在部门置为null
	 * @param departmentIdList 部门id集合
	 * @return
	 */
	public int setNullDepartment(List<String> departmentIdList, Date date){
		
		if(Collections.isEmpty(departmentIdList)){
			return 0;
		}
		
		String jpql = "update user_enterprise_department_position uedp set uedp.department_id = null, uedp.update_time=:date where uedp.department_id in ";
		
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for(String t : departmentIdList){
			 sb.append(" '" + t + "',");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));//去掉最后的","
		sb.append(")");
		
		jpql += sb.toString();
		
		Query query = em.createNativeQuery(jpql);
		query.setParameter("date", date);
		return query.executeUpdate();
	}
	
	/**
	 * 查询两个用户共同所在的公司id
	 * @param userId1 用户id
	 * @param userId2 用户id
	 * @return
	 */
	public List<String> findEnterpriseIdByUsersInSameEnterprise(String userId1, String userId2){
		String jpql = " select enterprise_id"
				+ " from"
				+ " ("
					+ "select u1.enterprise_id from user_enterprise_department_position u1 where u1.user_id=:userId1"
					+ " UNION ALL"
					+ " select u2.enterprise_id from user_enterprise_department_position u2 where u2.user_id=:userId2"
				+ ") as u"
				+ " group by enterprise_id"
				+ " having count(enterprise_id) > 1";
		
		Query query = em.createNativeQuery(jpql);
		query.setParameter("userId1", userId1);
		query.setParameter("userId2", userId2);
		
		return query.getResultList();
	}

	/**
	 * 获取公司某些部门的人员id
	 * @param enterpriseId 公司id
	 * @param departmentIds 部门id集合
	 * @return
	 */
	public List<String> findUserIdByEnterpriseIdAndDepartmentIds(String enterpriseId, List<String> departmentIds){
		
		if(Collections.isEmpty(departmentIds)){
			return new ArrayList<String>();
		}
		
		String jpql = "select uedp.user_id"
				+ " from user_enterprise_department_position uedp"
				+ " where uedp.enterprise_id=:enterpriseId"
				+ " and uedp.department_id in ";
		
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for(String t : departmentIds){
			 sb.append(" '" + t + "',");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));//去掉最后的","
		sb.append(")");
		
		jpql += sb.toString();
		
		Query query = em.createNativeQuery(jpql);
		query.setParameter("enterpriseId", enterpriseId);
		
		return query.getResultList();
	}
	
}
